package com.spark.tools;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.spark.core.SparkContext;
import com.spark.core.XMap;
import com.spark.dao.SessionFactory;

public class Logger {
	
	private static final String DEFAULT_STATEMENT = "log_error.insert";
	
	@SuppressWarnings("unchecked")
	public static int log(String code, SparkContext context, Exception e){
		e.printStackTrace();
		Integer errorId = -1;
		try{
			SqlSession sqlSession = SessionFactory.getSession();
			XMap xmap = context.getParameter();
			Map map = new HashMap();
			StringWriter sw = new StringWriter();
		    PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			Integer userId = (Integer)context.getSession().get(SparkContext.FIELD_USER_ID);
			map.put("ERROR_CODE", code);
			map.put("CREATED_BY", userId);
			map.put("ERROR_CONTENT", sw.toString());
			map.put("PARAMETER", xmap.toXML());
			map.put("CREATED_BY_NAME", "");
			map.put("CREATION_DATE", new Date());
			sqlSession.insert(DEFAULT_STATEMENT, map);
			errorId = (Integer)map.get("ERROR_ID");
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return errorId;
	}
}
